//WEBSOCKET INIT AND HANDLERS
var webSocket;
var nickname;

function onMessage(event) {
    var message = JSON.parse(event.data);
    console.log("A message has been received:");
    console.log(message);
    if(message.type === 'chat'){
        printMessage(message.message, message.nickname);
    }else if(message.type === 'nickname'){
        nickname = message.nickname;
        document.getElementById("username").innerHTML = nickname;
    }else if(message.type === 'userslist'){
        setUserslist(message.userslist);
    }else if(message.type === 'private'){
        privateMessagePopup(message.message, message.sender);
    }
}

function onOpen() {
    document.getElementById("statusLine").innerHTML = "Connection established";
    document.getElementById("connectBtn").innerHTML = "Disconnect";
    sendNicknameMessage();
}

function onError(event) {
    alert(event.data);
}

function onClose(event){
    console.log("onClose() has been called upon!");
    document.getElementById("connectBtn").innerHTML = "Connect";
    document.getElementById("usersList").innerHTML = "";  
}

function start() {
    webSocket.send('hello');
    return false;
}

//Send the current text in the input textbox to the server (to all other peers)
function sendMessage() {
    var chatMessage = {
        type: null,
        nickname: null,
        message: null
    };
    chatMessage.type = "chat";
    chatMessage.message = document.getElementById("message").value;
    chatMessage.nickname = nickname;
    
    webSocket.send(JSON.stringify(chatMessage));
    printMessage(chatMessage.message, nickname);
    console.log("sendMessage has been called!");
}

//------------------------------SUPPORT METHODS---------------------------------

function privateMessagePopup(message, sender){
    var description = "Private message from " + sender 
    + ": " + message;
    var resp = window.prompt(description,"Write a response..");
    
    if(resp != 'Write a response..')
        sendPrivateMessage(resp, sender);
}

function sendPrivateMessage(msg, receiver){
    var pMsg = {
        type: "private",
        message: msg,
        receiver: receiver,
        sender: nickname
    };
    webSocket.send(JSON.stringify(pMsg));
}

function setUserslist(userlist){
    console.log("Userlist var:")
    console.log(userlist);
    
    var table = "<table border ='0'>";
    var tr = "<tr>";
    var _tr ="</tr>";
    var td = "<td>";
    var _td = "</td>";
    var _table ="</table>";
       
    var userslistHtml = table;   
    for (var i=0; i<userlist.length; i++){
        userslistHtml += tr+td + "<button style='background:none;" + 
        "border:none; margin:0; padding:0;' onclick='newPrivateMessage(&quot;" +
        userlist[i] + "&quot;)' >" + userlist[i] + "</button>" + _td + _tr;
    }
    userslistHtml += _table;
    document.getElementById("usersList").innerHTML = userslistHtml;   
}

function newPrivateMessage(username){
    var message = window.prompt("Send a private message to " + username+"." ,"Message..");
    sendPrivateMessage(message,username);
}

function connectBtn(){
    if (webSocket.readyState == 1){ // 1 is connected
        console.log("websocket.readyState is 1");
        disconnect();
    }else{
        console.log("websocket.readyState is 0");
        connect();
    }
}

function disconnect(){
    webSocket.close();
    document.getElementById("statusLine").innerHTML = "Disconnected";
}

function changeNickname(){
    setNicknameVariable();
    sendNicknameMessage();
}

function sendNicknameMessage(){
    var nicknameMessage = {
        type: "nickname",
        nickname: nickname
    };
    webSocket.send(JSON.stringify(nicknameMessage));
}

function setNicknameVariable(){
        while (true) {
        nickname = window.prompt("Please enter your nickname: ","");
        if (nickname == null || nickname.length <1)
            continue;
        else {
            break;
        }
    }
}

function closingCode(){
   window.onbeforeunload = null;
   websocket.close();
}

function printMessage(message, sender){
   var contentDiv = document.getElementById("contentDiv").innerHTML;
   var d = new Date();
   var n = d.toLocaleTimeString();  
   if(sender == nickname)
        contentDiv += ("<br/><b>" +"["+n+"] "+ sender +" : </b>" + message);
   else
       contentDiv += ("<br/>" +"["+n+"] "+ sender +" : " + message);
   document.getElementById("contentDiv").innerHTML = contentDiv;    
}

function onLoad(){
    window.onbeforeunload = closingCode; // attempt to make the websocket connection close properly

    setNicknameVariable();
    connect(); 
}

function connect(){
    webSocket = new WebSocket('ws://10.0.0.253:8080/websk/ws2');//127.0.0.1

    webSocket.onerror = function(event) {
        onError(event);
    };

    webSocket.onopen = function(event) {
        onOpen(event);
    };

    webSocket.onmessage = function(event) {
        onMessage(event);
    };

    webSocket.onclose = function(event){
        onClose(event);
    };
}